package com.gckj.dfds.backup;


import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 负责管理元数据的核心组件
 * @author zhonghuashishan
 *
 */
public class FSNamesystem {

	/**
	 * 负责管理内存文件目录树的组件
	 */
	private FSDirectory directory;

	/**
	 *  是否恢复完毕
	 */
	private volatile boolean finish = false;


	private Long checkPointerTxid = 0L;

	public FSNamesystem() {
		this.directory  = new FSDirectory();
		getCheckPointerTxidInfo();
		loadFsImage(checkPointerTxid);
		this.finish = true;
	}

	private void loadFsImage(Long checkPointerTxid) {
		if (checkPointerTxid != 0L) {
			try {
				byte[] bytes = Files.readAllBytes(Paths.get("D://dfs//images//image-" + checkPointerTxid + ".meta"));
				String fsImageJson = new String(bytes);
				this.directory.setDirTree(JSONObject.parseObject(fsImageJson, INode.class));
				System.out.println("在磁盘中恢复完成。。。。。。。。");
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public boolean isFinish() {
		return finish;
	}

	public void setFinish(boolean finish) {
		this.finish = finish;
	}

	public Long getCheckPointerTxid() {
		return checkPointerTxid;
	}

	public void setCheckPointerTxid(Long checkPointerTxid) {
		this.checkPointerTxid = checkPointerTxid;
	}

	private void getCheckPointerTxidInfo() {
		try {
			String checkPointerInfoPath = "D://dfs//back_check_pointer_txid.meta";
			File file = new File(checkPointerInfoPath);
			if (file.exists()) {
				byte[] bytes = Files.readAllBytes(Paths.get(checkPointerInfoPath));
				String info = new String(bytes);
				String[] split = info.split("_");
				this.checkPointerTxid = Long.parseLong(split[0]);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 创建目录
	 * @param path 目录路径
	 * @return 是否成功
	 */
	public Boolean mkdir(Long txid, String path) throws Exception {
		//
		this.directory.mkdir(txid, path);
		return true;
	}

	public Boolean createFile(Long txid, String path) {
		directory.createFile(txid, path);
		return true;
	}

	public FSDirectory getDirectory() {
		return directory;
	}

	public void setDirectory(FSDirectory directory) {
		this.directory = directory;
	}
}
